<template>
  <div class="login">
    <header>
        <span>登 录</span>
    </header>
    <main>
        <span>
            <img src="../img/1.gif" alt="">
        </span>
        <p><input type="text" placeholder="请输入用户名" v-model="ruleFrom.username"></p>
        <p><input type="password" placeholder="请输入密码" v-model="ruleFrom.password"></p>
        <button @click="login(ruleFrom)">立即登录</button>
        <button @click="register(ruleFrom)">注册</button>
    </main>
  </div>
</template>

<script>
import axios from '../../ulis/request'
export default {
    name:'login',
    data() {
        return {
            ruleFrom:{
                username:'',
                password:''
            },
        }
    },
    methods:{
        //登录
        login(ruleFrom){
            axios({
                url:'/api/login',
                method:'post',
                data:{
                    username:ruleFrom.username,
                    password:ruleFrom.password
                }
            }).then(res => {
                console.log(res);
                
                if(res.data.code === 1){
                    alert('登录成功')
                    console.log(res);
                    
                    sessionStorage.setItem('token',res.data.token) //将token保存在本地

                    //将数据保存到本地
                    sessionStorage.setItem('name',res.data.datas[0].name)
                    sessionStorage.setItem('username',res.data.datas[0].username)
                    sessionStorage.setItem('url',res.data.datas[0].url)
                    this.$router.push('/')
                }else{
                    alert('账号或密码错误')
                }
            })
        },

        //注册
        register(ruleFrom){
            axios({
                url:'/api/register',
                method:'post',
                data:{
                    username:ruleFrom.username,
                    password:ruleFrom.password
                }
            }).then(res => {
                if(res.data.code === 1){
                    alert('注册成功')
                }else{
                    alert('账号或密码错误')
                }
            })
        }
    }
}
</script>

<style>
.login{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.login header{
    width: 100%;
    height: 60px;
    background-color: #1d8bf7;
    text-align: center;
    line-height: 60px;
    color: white;
    font-size: 20px;
}

.login main{
    flex: 1;
    overflow-y: auto;
    text-align: center;
}

.login main img{
    margin-top: 30px;
}

.login main p{
    margin-top: 10px;
}

.login main input{
    width: 300px;
    height: 40px;
    border: 1px solid #ccc;
    border-radius: 6px;
    outline: none;
}

.login main button{
    width: 300px;
    height: 40px;
    border-radius: 6px;
    border: 1px solid #169bd5;
    outline: none;
    background-color: #169bd5;
    color: white;
    margin-top: 10px;
}
</style>